package com.interview.filter;

import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author ljh
 * @version 1.0
 * @date 2021/5/5 09:40
 * @description 标题
 * @package com.itheima.gatewayadmin.filter
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //3.获取当前的请求路径 判断是否是登录的请求 如果是 放行    /admin/admin/login
        String path = request.getURI().getPath();
        //如果以/admin/admin/login
        if(path.startsWith("/user/userLogin/login")){
            return chain.filter(exchange);
        }
        //4.获取【请求头 头名：token】中的令牌数据
        //token的值：xxxx.yyyy.zzz
        String token = request.getHeaders().getFirst("token");
        //5.判断如果为null 返回错误
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//请求完成
        }
        //6.校验令牌是否正确（用jwt来进行校验） 如果错误 返回错误
       if( SystemConstants.JWT_OK!= AppJwtUtil.verifyToken(token)){
           response.setStatusCode(HttpStatus.UNAUTHORIZED);
           return response.setComplete();//请求完成
       }

       //校验当前令牌的所属的角色是否是 admin
        //7.校验正确(需要解析令牌的信息) 放行  todo
        return chain.filter(exchange);
    }

    //数字越小 优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
